const mongoose = require("mongoose")
const md5 = require('blueimp-md5')
mongoose.connect('mongodb://localhost:27017/blog', {useUnifiedTopology: true, useNewUrlParser: true});

//设计集合结构
const userSchema = new mongoose.Schema({
    nickname: {
        type: String,
        required: true //必填
    },
    password: {
        type: String,
        required: true //必填
    },
    email: {
        type: String,
        required: true //必填
    },
    create_time: {
        type: Date,
        //不能接Date.now(),会立即调用造成时间错误, 使用Date.now则不会
        default: Date.now
    },
    create_modify_time: {
        type: Date,
        default: Date.now
    },
    avatar: {
        type: String,
        default: "/public/img/avatar-default.png"
    },
    bio: {
        type: String,
        default: ""
    },
    gender: {
        type: Number,
        default: 0,
        enum: [0, 1],
    },
    birthday: {
        type: Date,
    },
    status: {
        type: Number,
        /**
         * 0:没有权限限制
         * 1:没有评论权限
         * 0:没有登录权限
         */
        enum: [0, 1, 2],
        default: 0
    }
})

const User = mongoose.model('User', userSchema);


exports.register = (user) => {
    return new Promise((resolve, reject) => {
        //加密
        user.password = md5(md5(user.password))

        //保存
        let registerUser = new User(user)
        registerUser.save().then(res => {
            resolve(res)
        }).catch(res => {
            reject("服务器错误")
        })
    })
}


exports.checkEmailExist = (email) => {
    return new Promise((resolve, reject) => {
        User.findOne({email: email}, function (error, res) {
            if (error) {
                return reject("服务器错误")
            }
            if (res) {
                return reject("邮箱已存在")
            }
            return resolve()
        })
    })
}

exports.checkNicknameExist = (nickname) => {
    return new Promise((resolve, reject) => {
        User.findOne({nickname: nickname}, function (error, res) {
            if (error) {
                return reject("服务器错误")
            }
            if (res) {
                return reject("用户名已存在")
            }
            return resolve()
        })
    })
}

exports.login = (user) => {
    return new Promise((resolve, reject) => {
        User.findOne({email: user.email, password: md5(md5(user.password))}, function (error, res) {
            if (error) {
                return reject("服务器错误")
            }
            if (!res) {
                return reject("登录失败,账号或密码错误")
            }
            resolve(res)
        })
    })
}
